/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GamePlay;

import Objects.Bottle;
import Resources.InputKey;
import Screens.IScreen;
import Screens.Menu;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;

/**
 *
 * @author ThanhTrung
 */
public class CanvasGame extends Canvas implements Runnable {

    public CanvasGame(MIDletGame midletGame) {
        Runtime.getRuntime().gc();
        this.setFullScreenMode(true);
        this.midletGame = midletGame;
        this.screen = new Menu(this);
        start();
    }

    public MIDletGame getMidletGame() {
        return midletGame;
    }

    public void setMidletGame(MIDletGame midletGame) {
        this.midletGame = midletGame;
    }

    public IScreen getScreen() {
        return screen;
    }

    public void setScreen(IScreen screen) {
        this.screen = screen;
    }

    public void start() {
        Thread runner = new Thread(this);
        runner.setPriority(Thread.MAX_PRIORITY);
        runner.start();
    }

    protected void paint(Graphics g) {
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(255,255,255);
        screen.paint(g);
    }

    public void run() {
        while (running) {
            long startTime = System.currentTimeMillis();
            long timeSinceStart = 0;
            serviceRepaints();
            repaint();
            
            timeSinceStart = System.currentTimeMillis() - startTime;
            if (timeSinceStart < MS_PER_FRAME) {
                try {
                    Thread.sleep(MS_PER_FRAME - timeSinceStart);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    protected void keyPressed(int keyCode) {
        screen.keyEvent(keyCode, InputKey.KEY_EVENT_DOWN);
    }

    protected void keyReleased(int keyCode) {
      screen.keyEvent(keyCode , InputKey.KEY_EVENT_UP);
    }

    protected void keyRepeated(int keyCode) {
        super.keyRepeated(keyCode);
        keyPressed(keyCode);
    }

    
    private MIDletGame midletGame;
    private IScreen screen;
    public static boolean running = true;
    private static final int MS_PER_FRAME = 30;    
}
